package org.example.springboot.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.example.springboot.constant.CommentStatusConstant;
import org.example.springboot.entity.Book;
import org.example.springboot.entity.Comment;
import org.example.springboot.entity.User;
import org.example.springboot.exception.ServiceException;
import org.example.springboot.mapper.BookMapper;
import org.example.springboot.mapper.CommentMapper;
import org.example.springboot.mapper.UserMapper;
import org.example.springboot.util.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 评论服务类
 */
@Service
public class CommentService {
    @Resource
    private CommentMapper commentMapper;
    
    @Resource
    private BookMapper bookMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 添加评论
     * @param bookId 图书ID
     * @param content 评论内容
     * @param parentId 父评论ID（回复评论时使用）
     * @return 评论ID
     */
    @Transactional(rollbackFor = Exception.class)
    public Long addComment(Long bookId, String content, Long parentId) {
        // 获取当前用户ID
        Long userId = JwtTokenUtils.getCurrentUser().getId();
        
        // 检查图书是否存在
        Book book = bookMapper.selectById(bookId);
        if (book == null) {
            throw new ServiceException("图书不存在");
        }
        
        // 如果是回复评论，检查父评论是否存在
        if (parentId != null) {
            Comment parentComment = commentMapper.selectById(parentId);
            if (parentComment == null || parentComment.getStatus().equals(CommentStatusConstant.DELETED)) {
                throw new ServiceException("回复的评论不存在或已被删除");
            }
            
            // 确保父评论和回复评论属于同一本书
            if (!parentComment.getBookId().equals(bookId)) {
                throw new ServiceException("回复评论与原评论不属于同一本书");
            }
        }
        
        // 创建评论
        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setBookId(bookId);
        comment.setContent(content);
        comment.setParentId(parentId);
        comment.setStatus(CommentStatusConstant.NORMAL);
        
        if (commentMapper.insert(comment) <= 0) {
            throw new ServiceException("评论失败");
        }
        
        return comment.getId();
    }
    
    /**
     * 删除评论
     * @param commentId 评论ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteComment(Long commentId) {
        // 获取当前用户ID
        Long userId = JwtTokenUtils.getCurrentUser().getId();
        
        // 检查评论是否存在
        Comment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            throw new ServiceException("评论不存在");
        }
        
        // 检查是否有权限删除（只能删除自己的评论）
        if (!comment.getUserId().equals(userId)) {
            throw new ServiceException("没有权限删除该评论");
        }
        
        // 逻辑删除评论（将状态设为已删除）
        comment.setStatus(CommentStatusConstant.DELETED);
        if (commentMapper.updateById(comment) <= 0) {
            throw new ServiceException("删除评论失败");
        }
    }
    
    /**
     * 管理员删除评论
     * @param commentId 评论ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void adminDeleteComment(Long commentId) {
        // 检查评论是否存在
        Comment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            throw new ServiceException("评论不存在");
        }
        
        // 逻辑删除评论（将状态设为已删除）
        comment.setStatus(CommentStatusConstant.DELETED);
        if (commentMapper.updateById(comment) <= 0) {
            throw new ServiceException("删除评论失败");
        }
    }
    
    /**
     * 获取图书评论列表（包含回复）
     * @param bookId 图书ID
     * @param currentPage 当前页
     * @param size 每页大小
     * @return 评论分页列表
     */
    public Page<Comment> getBookComments(Long bookId, Integer currentPage, Integer size) {
        // 查询主评论
        Page<Comment> commentPage = commentMapper.getCommentsByBookId(new Page<>(currentPage, size), bookId);
        
        // 查询每个主评论的回复
        for (Comment comment : commentPage.getRecords()) {
            List<Comment> replies = commentMapper.getRepliesByParentId(comment.getId());
            comment.setReplies(replies);
        }
        
        return commentPage;
    }
    
    /**
     * 获取用户的评论列表
     * @param currentPage 当前页
     * @param size 每页大小
     * @return 评论分页列表
     */
    public Page<Comment> getUserComments(Integer currentPage, Integer size) {
        // 获取当前用户ID
        Long userId = JwtTokenUtils.getCurrentUser().getId();
        
        // 查询用户的评论
        Page<Comment> page = new Page<>(currentPage, size);
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<Comment>()
            .eq(Comment::getUserId, userId)
            .eq(Comment::getStatus, CommentStatusConstant.NORMAL)
            .orderByDesc(Comment::getCreateTime);
        
        return commentMapper.selectPage(page, queryWrapper);
    }
    
    /**
     * 获取所有评论（管理员用）
     * @param bookId 图书ID（可选）
     * @param currentPage 当前页
     * @param size 每页大小
     * @return 评论分页列表
     */
    public Page<Comment> getAllComments(Long bookId, Integer currentPage, Integer size) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<Comment>()
            .eq(bookId != null, Comment::getBookId, bookId)
            .orderByDesc(Comment::getCreateTime);

        Page<Comment> commentPage = commentMapper.selectPage(new Page<>(currentPage, size), queryWrapper);
        List<Comment> records = commentPage.getRecords();
        records.forEach(this::fillRelateInfo);
        commentPage.setRecords(records);
        return commentPage;
    }

    private void fillRelateInfo(Comment comment) {
        if(comment.getUserId()!=null){
            User user = userMapper.selectById(comment.getUserId());
            comment.setUsername(user.getUsername());
            comment.setAvatar(user.getAvatar());


        }
        if(comment.getBookId()!=null){
            Book book = bookMapper.selectById(comment.getBookId());
            comment.setBookTitle(book.getTitle());
            comment.setBookCover(book.getCoverUrl());
        }

    }
} 